package com.example.administrator.gaodemap;

import android.content.Context;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

public class LocationManager {
    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption option = null;
    static volatile LocationManager mLocationManager;

    private LocationManager() {
    }

    public static LocationManager getInstance() {
        if (mLocationManager == null) {
            synchronized (LocationManager.class) {
                if (mLocationManager == null) {
                    mLocationManager = new LocationManager();
                }
            }
        }
        return mLocationManager;
    }

    public void startLocation(Context context) {
        //初始化定位
        mLocationClient = new AMapLocationClient(context.getApplicationContext());
//设置定位回调监听
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
//可在其中解析amapLocation获取相应内容。
                        Log.e("$zhw======$",aMapLocation.toString());

                    }else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError","location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });
        option = new AMapLocationClientOption();
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
//        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
//        if (null != mLocationClient) {
//            mLocationClient.setLocationOption(option);
//            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
//            mLocationClient.stopLocation();
//            mLocationClient.startLocation();
//        }

//会同时使用网络定位和GPS定位，优先返回最高精度的定位结果，以及对应的地址描述信息
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        Wi-Fi和基站定位
//        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
//        不需要连接网络，只使用GPS进行定位
//        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);

        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
//        option.setInterval(1000);
        //获取一次定位结果：
//        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
//启动定位
        mLocationClient.startLocation();
    }
    public void stopLocation(){
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
    }
}
